package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entiey.Brand;
import com.leyou.item.entiey.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper,Brand> implements BrandService {


    @Autowired
    private CategoryBrandService categoryBrandService;



    //分页查询品牌
    //前端需要数据  总条数  分页数据  分页大小
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        //分页健壮性
        page = Math.max(page,1);
        rows = Math.max(rows,5);
        //分页
        Page<Brand> pageInfo = new Page<>(page, rows);
//
//        //判断key是否为空
//        if (!StringUtils.isEmpty(key)){
//            query().like("name",key).or()
//                    .eq("letter",key).page(pageInfo);
//        }


        // .判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        // .如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists,"letter", key)
                .page(pageInfo);

        //封装结果
        return new PageDTO<>(pageInfo.getTotal(),pageInfo.getPages(),BrandDTO.convertEntityList(pageInfo.getRecords()));
    }


    //根据分类id查询品牌
    @Override
    public List<BrandDTO> queryBrandsByCategoryId(Long id) {
        //根据分类id在中间表中查找品牌id的集合
        //select brand_id from tb_brand_category where category_id = #{id}
        List<CategoryBrand> CategoryBrandList = categoryBrandService.query().eq("category_id", id).list();

        //获取brand_id
        List<Long> brandList = CategoryBrandList.stream()
                .map(CategoryBrand::getBrandId).collect(Collectors.toList());

        //根据品牌id的集合查找品牌信息
        //select * from tb_brand where brand_id in （）
        List<Brand> brands = this.listByIds(brandList);

        return BrandDTO.convertEntityList(brands);
    }

    //新增品牌  设计多张表更改  开始事务
    @Transactional
    @Override
    public void addBatch(BrandDTO brandDTO) {
        //1.品牌表 需将DTO转换为entity类型
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean success = this.save(brand);
        if (!success) {
            // 添加失败，抛出异常
            throw new LyException(500,"添加品牌失败!");
        }
        //2.中间表
        //获取分类id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //封装中间表对象集合
        Long brandId = brand.getId();
        //遍历list集合
        ArrayList<CategoryBrand> list = new ArrayList<>(categoryIds.size());
        for (Long categoryId : categoryIds) {
            //创建中间表对象
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            list.add(categoryBrand);
        }

//        // 封装中间表对象的集合
//        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
//                .map(id -> CategoryBrand.of(id, brand.getId()))
//                .collect(Collectors.toList());
        //批量插入数据
        success = categoryBrandService.saveBatch(list);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500,"添加品牌失败!");
        };

    }

    //修改品牌信息
    @Transactional
    @Override
    public void updateBrand(BrandDTO brandDTO) {
        //修改品牌表  转为为entity对象
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean isSuccess = this.updateById(brand);
        if (!isSuccess){
            throw new LyException(500,"更新品牌失败!");
        }
        // 根据品牌id删除中间表数据
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<CategoryBrand>();
        wrapper.eq("brand_id",brandDTO.getId());
        isSuccess = categoryBrandService.remove(wrapper);
        if (!isSuccess) {
            // 更新失败，抛出异常
            throw new LyException(500,"更新品牌失败，删除中间表数据出错!");
        }
        //中间表重新加入数据
        List<Long> categoryIds = brandDTO.getCategoryIds();
        List<CategoryBrand> list = categoryIds.stream().map(id -> CategoryBrand.of(id, brandDTO.getId())).collect(Collectors.toList());
        isSuccess = categoryBrandService.saveBatch(list);
        if (!isSuccess) {
            // 更新失败，抛出异常
            throw new LyException(500,"更新品牌失败！");
        }

    }



    //删除品牌信息
    @Override
    @Transactional
    public void deleteBrand(Long id) {
        //删除品牌表
        boolean success = this.removeById(id);
        if (!success)   throw new LyException(500,"删除品牌信息失败！");

        //删除中间表
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id",id);
        success = categoryBrandService.remove(wrapper);
        if (!success)   throw new LyException(500,"删除品牌信息失败！");
    }


}
